﻿using log4net;
using MySql.Data.MySqlClient;
using server.Business;
using server.Model;
using server.Tool;
using System;
using System.Collections.Generic;

namespace server.DAO
{
   public  class GrounpDao
    {
        private GrounpLifeDao grounpLifeDao = new GrounpLifeDao();
        private PublishPlayerState publishPlayerState = new PublishPlayerState();
        private ILog Logger = log4net.LogManager.GetLogger("server.DAO.GrounpDao");
        public string StartGame(string grounpId)
        {
            grounpId = grounpId.Trim();
            string stateResult = CheckGameReadyState(grounpId);
            if(!stateResult.Equals("-1"))
            {
                return stateResult;
            }

            string sql = "select * from grounp where id = @grounpId";
            List<Grounp> result = MySqlExecuteTools.GetObjectResult<Grounp>(sql,
                new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });


            sql = "update  grounp set runState =0  where id = @grounpId;";
            MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });

            //推送给该组的其他玩家更新状态

            publishPlayerState.SendUserListByAdmin(result[0].userId, PublishPlayerState.Update_Command);

            //grounp_life 复制到life表中
            grounpLifeDao.SetGrounpLifeToUserList(grounpId);
            return "0";
        }


        /// <summary>
        /// 检查游戏准备就绪
        /// </summary>
        /// <param name="grounpId"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public string CheckGameReadyState(string grounpId)
        {
            grounpId = grounpId.Trim();
            string sql = "select * from grounp where id = @grounpId";
            List<Grounp> result = MySqlExecuteTools.GetObjectResult<Grounp>(sql,
                new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });

            if (result.Count == 1)
            {
                if (result[0].fenceLat <= 0)
                {
                    return "电子围栏尚未设置，无法启动游戏！";
                }
                //查询用户的命值时候初始化完成

                Grounp_Life brounp_Life = grounpLifeDao.GetGrounpByPKId(grounpId);

                if ((brounp_Life == null) || brounp_Life.lifeValue == 0 || brounp_Life.bulletCount == 0)
                {
                    return "用户的命值信息未初始化完成，无法启动游戏";
                }
                //查询grounp下room 的状态
                sql = "select * from room where grounpId = @grounpId";
                int roomCount = MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });

                if (roomCount == 0)
                {
                    return "该游戏未创建战队，无法启动游戏";
                }
                if(roomCount == 1)
                {
                    return "操作失败，游戏必须创建至少两个战队。";
                }


                sql = "select * from room where grounpId = @grounpId and  runState = -1";
                int resultCount = MySqlExecuteTools.GetCountResult(sql, new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });
                if (resultCount > 0)
                {

                    return "该游戏的队员尚未准备就绪，无法启动游戏";
                }

            }
            else
            {
                return "非法操作";
            }

            return "-1";
        }


        /// <summary>
        /// 检查游戏设置是否完成
        /// </summary>
        /// <param name="grounpId"></param>
        /// <param name="result"></param>
        /// <returns></returns>
        public string CheckGameIsSetFinish(string grounpId)
        {
            grounpId = grounpId.Trim();
            string sql = "select * from grounp where id = @grounpId";
            List<Grounp> result = MySqlExecuteTools.GetObjectResult<Grounp>(sql,
                new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });

            if (result.Count == 1)
            {
                if (result[0].fenceLat <= 0)
                {
                    return "电子围栏尚未设置，无法启动游戏！";
                }
                //查询用户的命值时候初始化完成

                Grounp_Life brounp_Life = grounpLifeDao.GetGrounpByPKId(grounpId);

                if ((brounp_Life == null) || brounp_Life.lifeValue == 0 || brounp_Life.bulletCount == 0)
                {
                    return "用户的命值信息未初始化完成，无法启动游戏";
                }
                //查询grounp下room 的状态
              
            }
            else
            {
                return "非法操作";
            }

            return "-1";
        }


        public string GetRemainTime(string userId, string userType)
        {
            userId = userId.Trim();
            userType = userType.Trim();
           // Console.WriteLine("userId={0},userType={1}", userId, userType);
            string sql = "";
            //管理员
            if (userType.Equals("1"))
            {
                sql = "select * from grounp where userId = @userId  and runState = 0";
                List<Grounp> pList = MySqlExecuteTools.GetObjectResult<Grounp>(sql, new MySqlParameter[] { new MySqlParameter("@userId", userId) });
                if (pList.Count > 0)
                {
                    return pList[0].remainTime.ToString();
                }
            }
            //玩家
            else
            {
                sql = "select p.remainTime from grounp p JOIN room r on p.id = r.grounpId join room_user ru on r.id = ru.room_id where ru.user_id =" + userId;
                List<object> list = MySqlExecuteTools.GetSingleFieldResult(sql, null);
                if (list != null && list.Count > 0)
                {
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    return  list[0].ToString();
                }
            }
            return "";

        }

        public string GetFireRemainTime(string userId, string userType)
        {
            //Logger.InfoFormat("userType={0},userid={1}", userType, userId);
            userType = userType.Trim();
            userId = userId.Trim();
            //管理员
            if (userType.Equals("1"))
            {
                
                string sql = "select * from grounp where userId = @userId  and runState = 0";
                List<Grounp> pList = MySqlExecuteTools.GetObjectResult<Grounp>(sql, new MySqlParameter[] { new MySqlParameter("@userId", userId) });
                if (pList.Count > 0)
                {
                    Grounp grounp= pList[0];
                    int remainTime = grounp.remainTime;
                    //开火时间
                    int fireTime = grounp.fireTime * 60;
                    //游戏总时间
                    int playerTime = grounp.playerTime * 60;
                    int _value = fireTime - (playerTime - remainTime);
                    if (_value <= 0)
                    {
                        _value = 10;
                    }
                   // Logger.InfoFormat("_value={0}", _value);
                    return _value.ToString();

                }
            }
            //玩家
            else
            {
                string sql = "select p.remainTime,p.fireTime,p.playerTime from grounp p JOIN room r on p.id = r.grounpId join room_user ru on r.id = ru.room_id where ru.user_id =" + userId;
                List<object> list = MySqlExecuteTools.GetMuchFieldResult(sql, null);
                if (list != null && list.Count > 0)
                {
                    List<object> itemList = (List<object>)list[0];
                    //秒
                    int remainTime = int.Parse(itemList[0].ToString());
                    //开火时间
                    int fireTime = int.Parse(itemList[1].ToString()) * 60;
                    //游戏总时间
                    int playerTime = int.Parse(itemList[2].ToString()) * 60;
                    int _value = fireTime - (playerTime - remainTime);
                    if (_value <= 0)
                    {
                        _value = 10;
                    }

                    return _value.ToString();

                }
            }

            return "0";
        }

        /// <summary>
        /// 0为尚未开火 ，1 为已经开火了
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userType"></param>
        /// <returns></returns>
        internal string IsFireTime(string userId, string userType)
        {
            userId = userId.Trim();
            userType = userType.Trim();
            //管理员
            if (userType.Equals("1"))
            {
                string sql = "select * from grounp where userId = @userId  and runState = 0";
                List<Grounp> pList = MySqlExecuteTools.GetObjectResult<Grounp>(sql, new MySqlParameter[] { new MySqlParameter("@userId", userId) });
                if (pList.Count > 0)
                {
                    Grounp grounp = pList[0];
                    int remainTime = grounp.remainTime;
                    //开火时间
                    int fireTime = grounp.fireTime * 60;
                    //游戏总时间
                    int playerTime = grounp.playerTime * 60;
                    if ((playerTime - remainTime) >= fireTime)
                    {
                        return "1";
                    }
                    else
                    {
                        return "0"; ;
                    }

                }

                return "-1";
            }
            else
            {
                string sql = "select p.remainTime,p.fireTime,p.playerTime from grounp p JOIN room r on p.id = r.grounpId join room_user ru on r.id = ru.room_id where ru.user_id =" + userId;
                List<object> list = MySqlExecuteTools.GetMuchFieldResult(sql, null);
                if (list != null && list.Count > 0)
                {
                    List<object> itemList = (List<object>)list[0];
                    //秒
                    int remainTime = int.Parse(itemList[0].ToString());
                    //开火时间单位为秒
                    int fireTime = int.Parse(itemList[1].ToString()) * 60;

                    //游戏总时间单位为秒
                    int playerTime = int.Parse(itemList[2].ToString()) * 60;
                    if ((playerTime - remainTime) >= fireTime)
                    {

                        return "1";
                    }
                    else
                    {
                        return "0"; ;
                    } 
                }
            }
                return "-1";
        }
        //判断管理端是否开发

        public string IsAdminFire(string grounpId)
        {
            Logger.InfoFormat("grounpId={0}", grounpId);
            grounpId = grounpId.Trim();
            string sql = "select * from grounp where id = @grounpId";
            List<Grounp> result = MySqlExecuteTools.GetObjectResult<Grounp>(sql,new MySqlParameter[] { new MySqlParameter("@grounpId", grounpId) });
            if (result.Count == 1)
            {
                Grounp grounp = result[0];
                int remainTime = grounp.remainTime;
                int fireTime = grounp.fireTime *60;
                int playerTime  = grounp.playerTime * 60;
                if ((playerTime - remainTime) >= fireTime)
                {
                    return "1";
                }
                else
                {
                    return "0"; ;
                }


            }
            return "0";
        }
    }
}
